package com.jerry.config;

import com.jerry.annotation.CurrentUser;
import com.jerry.common.constant.Constants;
import com.jerry.token.model.TokenModel;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * Filename:    com.lngtop.zc.config.CurrentUserResolver
 * Description:
 * Copyright:   Copyright (c)2016
 * Company:     lngtop
 *
 * @author: 谢余锋
 * @version: 1.0
 * Create at:   2016/12/28 上午11:01
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016/12/28      谢余锋        1.0        1.0 Version
 */
public class CurrentUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        TokenModel tokenModel = (TokenModel) nativeWebRequest.getAttribute(Constants.CURRENT_USER, RequestAttributes.SCOPE_REQUEST);
        if (tokenModel == null) {
            throw new MissingServletRequestPartException("Missing Current User");
        }

        if (methodParameter.getParameterType().isAssignableFrom(TokenModel.class)) {
            return tokenModel;
        }

        throw new MissingServletRequestPartException("No Argument Can Set For Current User");
    }
}
